package com.wms.execcmd;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

public class Ping {
	/*
	 * logger
	 */
	Logger logger =  Logger.getLogger(Ping.class);
	/*
	 *  Set reader to read stdout
	 */
	DefaultOutputReader stdoutReader = new DefaultOutputReader(logger);


   /*
    * Set reader to read stderr
    */
	DefaultOutputReader stderrReader = new DefaultOutputReader(logger);
	
	
	/*
	 * String for save output and error
	 */
	String stdout=null;
	String stderr=null;
	
	public Ping() {
		
		super();
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * call ping command
	 * @parmes ip address
	 * @return -1 flase. 0 ping ok
	 */
	public int PingHost(String ip){
		CommandWrapper cmdwrapper = new CommandWrapper(logger);
		String cmd=null;
		if(System.getProperty("os.name").indexOf("Windows")!=-1)
		{
			cmd = "ping -n 3 " + ip;
		}
		else
			cmd = "ping -c 3 " + ip;
		
		Map<String , String > envmap = System.getenv();
		String [] envp =mapToEnvParams(envmap) ;
		int ret=-1; 
		try{

			cmdwrapper.setStdoutReader(stdoutReader);
			cmdwrapper.setStderrReader(stderrReader);
			ret=cmdwrapper.exec(cmd.split(" "), envp, -1);
		}catch(Exception e)
		{
			
		}
		stdout = stdoutReader.getBuffer().toString();
		stderr = stderrReader.getBuffer().toString();
		return ret;
	}
	/**
	 * Convert map the environment parameters required by command-line execution
	 *
	 * @param params
	 * @return
	 */
	public static String[] mapToEnvParams(Map<String, String> params) {
		if (params == null) {
			return null;
		}
		
		String[] envp = new String[params.size()];
		int index = 0;

		for (Map.Entry<String, String> entry : params.entrySet()) {
			String name = entry.getKey();
			String value = entry.getValue();
			envp[index] = name + "=" + value;
	
			index++;
		}
		return envp;
	}

	/**
	 * parse output
	 */
	private boolean parsestdout()
	{
		if(stdout!=null && (stdout.indexOf("time=")>0 ||stdout.indexOf("time<")>0))
		{
			return true;
		}
		else
		return false;
		
	}
	/**
	 *  JSP page can cal this public function
	 *  return : true-- ping ok
	 *           false-- ping failed
	 */
	public boolean PingTest(String ip)
	{
		if(PingHost(ip)!=0){
			logger.error(this.stderr);
			//System.out.println(this.stderr);
			return false;
		}
			
		return parsestdout();
		
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Ping test = new Ping();
		System.out.println(test.PingTest("labp01"));
	}

}
